<script setup lang="ts">
import { ref, reactive, onMounted, h } from "vue";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { deviceDetection } from "@pureadmin/utils";
import dayjs from "dayjs";

import Delete from "@iconify-icons/ep/delete";
import EditPen from "@iconify-icons/ep/edit-pen";
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";
import AddFill from "@iconify-icons/ri/add-circle-line";
import View from "@iconify-icons/ep/view";

import PositionForm from "./form.vue";
import { AdPositionProps } from "../utils/types";
import { getAdPositionStatusTagType, getAdPositionTypeTagType } from "../utils/types";

defineOptions({
  name: "AdPosition"
});

const formRef = ref();
const tableRef = ref();
const form = reactive({
  name: "",
  code: "",
  type: null,
  status: null
});

const dataList = ref<AdPositionProps[]>([]);
const loading = ref(true);
const { tagStyle } = usePublicHooks();

const pagination = reactive<PaginationProps>({
  total: 0,
  pageSize: 10,
  currentPage: 1,
  background: true
});

// 广告位类型文本映射
const AdPositionTypeText = {
  1: "横幅广告",
  2: "侧边栏广告",
  3: "弹窗广告",
  4: "浮动广告",
  5: "内容页广告"
};

// 状态文本映射
const StatusText = {
  0: "禁用",
  1: "启用"
};

const columns: TableColumnList = [
  {
    label: "勾选列",
    type: "selection",
    width: 55,
    align: "left",
    hide: ({ checkList }) => !checkList.includes("勾选列")
  },
  {
    label: "序号",
    type: "index",
    width: 70,
    hide: ({ checkList }) => !checkList.includes("序号")
  },
  {
    label: "广告位名称",
    prop: "name",
    minWidth: 150,
    cellRenderer: ({ row, props }) => (
      <el-link
        class="no-pager"
        size={props.size}
        type="primary"
        underline={false}
        style={{
          fontSize: props.size === "small" ? "12px" : "14px",
          marginRight: "4px"
        }}
        onClick={() => openDialog("查看", row)}
      >
        {row.name}
      </el-link>
    )
  },
  {
    label: "广告位编码",
    prop: "code",
    minWidth: 120,
    cellRenderer: ({ row }) => (
      <el-tag size="small" type="info">
        {row.code}
      </el-tag>
    )
  },
  {
    label: "广告位类型",
    prop: "type",
    minWidth: 120,
    cellRenderer: ({ row, props }) => (
      <el-tag
        size={props.size === "small" ? "small" : "default"}
        type={getAdPositionTypeTagType(row.type)}
      >
        {AdPositionTypeText[row.type]}
      </el-tag>
    )
  },
  {
    label: "尺寸",
    prop: "size",
    minWidth: 100,
    cellRenderer: ({ row }) => (
      <div class="text-sm">
        {row.width && row.height ? `${row.width} × ${row.height}` : "未设置"}
      </div>
    )
  },
  {
    label: "状态",
    prop: "status",
    minWidth: 100,
    cellRenderer: ({ row, props }) => (
      <el-tag
        size={props.size === "small" ? "small" : "default"}
        type={getAdPositionStatusTagType(row.status)}
      >
        {StatusText[row.status]}
      </el-tag>
    )
  },
  {
    label: "页面位置",
    prop: "pagePosition",
    minWidth: 120
  },
  {
    label: "排序",
    prop: "sort",
    minWidth: 80
  },
  {
    label: "创建时间",
    prop: "createTime",
    minWidth: 180,
    formatter: ({ createTime }) =>
      dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
  },
  {
    label: "操作",
    fixed: "right",
    width: 180,
    slot: "operation"
  }
];

// 生成模拟广告位数据
function generateMockPositions(): AdPositionProps[] {
  const mockData: AdPositionProps[] = [];
  const names = ["首页横幅", "侧边栏广告", "内容页广告", "弹窗广告", "浮动广告", "底部横幅", "顶部通知栏", "文章内广告"];
  const codes = ["home_banner", "sidebar_ad", "content_ad", "popup_ad", "floating_ad", "footer_banner", "top_notice", "article_ad"];
  const pagePositions = ["首页", "列表页", "详情页", "全站", "用户中心"];
  
  for (let i = 0; i < names.length; i++) {
    mockData.push({
      id: i + 1,
      name: names[i],
      code: codes[i],
      type: (i % 5) + 1,
      description: `${names[i]}的描述信息`,
      width: [728, 300, 970, 320, 250][i % 5],
      height: [90, 250, 250, 480, 250][i % 5],
      status: Math.random() > 0.3 ? 1 : 0,
      pagePosition: pagePositions[i % pagePositions.length],
      sort: (i + 1) * 10,
      createTime: dayjs().subtract(Math.floor(Math.random() * 30), "day").format("YYYY-MM-DD HH:mm:ss"),
      updateTime: dayjs().subtract(Math.floor(Math.random() * 10), "day").format("YYYY-MM-DD HH:mm:ss"),
      remark: `备注信息${i + 1}`
    });
  }
  return mockData;
}

// 搜索
async function onSearch() {
  loading.value = true;
  try {
    // 模拟API调用
    const mockData = generateMockPositions();
    
    // 模拟搜索过滤
    let filteredData = mockData;
    if (form.name) {
      filteredData = filteredData.filter(item => 
        item.name.toLowerCase().includes(form.name.toLowerCase())
      );
    }
    if (form.code) {
      filteredData = filteredData.filter(item => 
        item.code.toLowerCase().includes(form.code.toLowerCase())
      );
    }
    if (form.type !== null && form.type !== "") {
      filteredData = filteredData.filter(item => item.type === form.type);
    }
    if (form.status !== null && form.status !== "") {
      filteredData = filteredData.filter(item => item.status === form.status);
    }
    
    // 模拟分页
    const total = filteredData.length;
    const start = (pagination.currentPage - 1) * pagination.pageSize;
    const end = start + pagination.pageSize;
    const pageData = filteredData.slice(start, end);
    
    dataList.value = pageData;
    pagination.total = total;
  } catch (error) {
    console.error("获取广告位列表失败:", error);
    message("获取广告位列表失败", { type: "error" });
  } finally {
    loading.value = false;
  }
}

// 重置表单
const resetForm = formEl => {
  if (!formEl) return;
  formEl.resetFields();
  onSearch();
};

// 删除广告位
function handleDelete(row) {
  ElMessageBox.confirm(
    `确认要删除广告位"${row.name}"吗？`,
    "删除确认",
    {
      type: "warning"
    }
  )
    .then(async () => {
      message("删除成功", { type: "success" });
      onSearch();
    })
    .catch(() => {});
}

// 批量删除
function handleBatchDelete(val) {
  if (val.length === 0) {
    message("请选择要删除的数据", { type: "warning" });
    return;
  }
  ElMessageBox.confirm(
    `确认要删除选中的 ${val.length} 个广告位吗？`,
    "批量删除确认",
    {
      type: "warning"
    }
  )
    .then(async () => {
      message("批量删除成功", { type: "success" });
      onSearch();
    })
    .catch(() => {});
}

// 分页
function handleSizeChange(val: number) {
  pagination.pageSize = val;
  onSearch();
}

function handleCurrentChange(val: number) {
  pagination.currentPage = val;
  onSearch();
}

function handleSelectionChange(val) {
  console.log("handleSelectionChange", val);
}

// 打开弹窗
function openDialog(title = "新增", row?: AdPositionProps) {
  addDialog({
    title: `${title}广告位`,
    props: {
      formInline: {
        id: row?.id ?? null,
        name: row?.name ?? "",
        code: row?.code ?? "",
        type: row?.type ?? 1,
        description: row?.description ?? "",
        width: row?.width ?? null,
        height: row?.height ?? null,
        status: row?.status ?? 1,
        pagePosition: row?.pagePosition ?? "",
        sort: row?.sort ?? 0,
        remark: row?.remark ?? ""
      }
    },
    width: "46%",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(PositionForm, { ref: formRef }),
    beforeSure: (done, { options }) => {
      const FormRef = formRef.value.getRef();
      const curData = options.props.formInline as AdPositionProps;
      function chores() {
        message(`您${title}了广告位名称为${curData.name}的这条数据`, {
          type: "success"
        });
        done(); // 关闭弹框
        onSearch(); // 刷新表格数据
      }
      FormRef.validate(valid => {
        if (valid) {
          console.log("curData", curData);
          // 实际开发中这里会调用新增和编辑接口
          chores();
        }
      });
    }
  });
}

onMounted(() => {
  onSearch();
});
</script>

<template>
  <div class="main">
    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px]"
    >
      <el-form-item label="广告位名称：" prop="name">
        <el-input
          v-model="form.name"
          placeholder="请输入广告位名称"
          clearable
          class="!w-[180px]"
        />
      </el-form-item>
      <el-form-item label="广告位编码：" prop="code">
        <el-input
          v-model="form.code"
          placeholder="请输入广告位编码"
          clearable
          class="!w-[180px]"
        />
      </el-form-item>
      <el-form-item label="广告位类型：" prop="type">
        <el-select
          v-model="form.type"
          placeholder="请选择广告位类型"
          clearable
          class="!w-[180px]"
        >
          <el-option label="横幅广告" :value="1" />
          <el-option label="侧边栏广告" :value="2" />
          <el-option label="弹窗广告" :value="3" />
          <el-option label="浮动广告" :value="4" />
          <el-option label="内容页广告" :value="5" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态：" prop="status">
        <el-select
          v-model="form.status"
          placeholder="请选择状态"
          clearable
          class="!w-[180px]"
        >
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon(Search)"
          :loading="loading"
          @click="onSearch"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <PureTableBar title="广告位列表" :columns="columns" @refresh="onSearch">
      <template #buttons>
        <el-button
          type="primary"
          :icon="useRenderIcon(AddFill)"
          @click="openDialog()"
        >
          新增广告位
        </el-button>
        <el-button
          type="danger"
          :icon="useRenderIcon(Delete)"
          @click="handleBatchDelete($refs.tableRef?.getSelectionRows())"
        >
          批量删除
        </el-button>
      </template>
      <template v-slot="{ size, dynamicColumns }">
        <pure-table
          ref="tableRef"
          border
          align-whole="center"
          showOverflowTooltip
          table-layout="auto"
          :loading="loading"
          :size="size"
          adaptive
          :data="dataList"
          :columns="dynamicColumns"
          :pagination="pagination"
          :paginationSmall="size === 'small' ? true : false"
          :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }"
          @selection-change="handleSelectionChange"
          @page-size-change="handleSizeChange"
          @page-current-change="handleCurrentChange"
        >
          <template #operation="{ row }">
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(View)"
              @click="openDialog('查看', row)"
            >
              查看
            </el-button>
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(EditPen)"
              @click="openDialog('编辑', row)"
            >
              编辑
            </el-button>
            <el-popconfirm
              :title="`是否确认删除广告位名称为${row.name}的这条数据`"
              @confirm="handleDelete(row)"
            >
              <template #reference>
                <el-button
                  class="reset-margin"
                  link
                  type="danger"
                  :size="size"
                  :icon="useRenderIcon(Delete)"
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </pure-table>
      </template>
    </PureTableBar>
  </div>
</template>

<style scoped lang="scss">
.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}
</style>